import sys
import pickle
import scipy.stats as stats
import statistics
import pandas as pd

#IMPORT BLOCK
save_handle = sys.argv[1]
files = sys.argv[2:]

unpickle =[[] for file in range(len(files))]

for file_num, file in enumerate(files):
	f = open(file,'rb')
	unpickle[file_num] = pickle.load(f)
	f.close()
	
onset_dict = unpickle[0]
onset_calc_dict = unpickle[1]
outlier_dict = unpickle[2]
time = unpickle[3]
smooth_events = unpickle[4]
signal_mean_dict = unpickle[5]
auc_dict = unpickle[6]

#SMOOTH TRACE OUTPUT
##Save smoothed traces to output file using pd DataFrame
title_line =['Event_' + str(i+1) for i in range(len(smooth_events))]
time_df = pd.DataFrame(time)
time_df.columns = ['Time (s)']
smooth_event_df = pd.DataFrame(smooth_events)
smooth_event_df = smooth_event_df.T
smooth_event_df.columns = title_line
smooth_concat_df = pd.concat([time_df,smooth_event_df], axis = 1)
smooth_concat_df.to_csv(save_handle + '_smooth_traces.csv')

#MAIN OUTPUT
##Create dict name lists for iteration
onset_dict_names = list(onset_dict.keys())
onset_calc_dict_names = list(onset_calc_dict.keys())
signal_mean_dict_names = list(signal_mean_dict.keys())

##Create and write title line to output file
title_line = ['Event Number', 'Peak Onset Index', 'Peak Onset Times (s)', 'Peak Onset Zscore', 'Max Peak Index', 'Max Peak Times (s)', 'Max Peak ZScore', 'Min Valley Index', 'Min Valley Time (s)', 'Min Valley Zscore', 'Onset to Peak Time (s)', '5s Signal Mean Zscore', '6s Signal Mean Zscore', 'AUC', 'Outlier Zscore', 'Outlier Flag', '', 'Mean Onset Time', 'Mean Onset SEM', 'Mean Onset to Peak Time', 'Mean Onset to Peak SEM', 'Mean Max Peak Zscore', 'SEM Max Peak Zscore', 'Mean Min Valley Zscore', 'SEM Min Valley Zscore', 'Mean 5s Signal Zscore','SEM 5s Signal Zscore', 'Mean 6s Signal Zscore','SEM 6s Signal Zscore', 'Mean AUC', 'SEM AUC']
novelty_peak_onset_output = open(save_handle + '_main_output.csv','w')
novelty_peak_onset_output.write(','.join(title_line) + '\n')


##Write first line to output file
first_line = 0
outlier_index = 0

for item_num, item in enumerate(onset_dict['Event Name']):
	current_line = []
	ev_name = onset_dict['Event Name'][item_num]
	if first_line == 0:
		first_line += 1
		if ev_name not in outlier_dict['Outlier Names']:
			current_line.append(ev_name)
			for name in onset_dict_names[1:]:
				current_line.append(str(onset_dict[name][item_num]))
			current_line.append(str(auc_dict['AUC'][item_num]))
			for blank in range(3):
				current_line.append('')
			for name in onset_calc_dict_names:
				current_line.append(str(onset_calc_dict[name]))
			for name in signal_mean_dict_names:
				current_line.append(str(signal_mean_dict[name]))
			current_line.append(str(auc_dict['Mean AUC']))
			current_line.append(str(auc_dict['SEM AUC']))
			novelty_peak_onset_output.write(','.join(current_line) + '\n')
		else:
			current_line.append(ev_name)
			for name in onset_dict_names[1:]:
				current_line.append(str(onset_dict[name][item_num]))
			current_line.append(str(auc_dict['AUC'][item_num]))
			current_line.append(str(outlier_dict['Outlier Zscore'][outlier_index]))
			current_line.append('*')
			current_line.append('')
			outlier_index += 1
			for name in onset_calc_dict_names:
				current_line.append(str(onset_calc_dict[name]))
			for name in signal_mean_dict_names:
				current_line.append(str(signal_mean_dict[name]))
			current_line.append(str(auc_dict['Mean AUC']))
			current_line.append(str(auc_dict['SEM AUC']))
			novelty_peak_onset_output.write(','.join(current_line) + '\n')

##Write subsequent lines to output file
for item_num, item in enumerate(onset_dict['Event Name'][1:]):
	current_line = []
	ev_name = onset_dict['Event Name'][item_num + 1]
	if ev_name not in outlier_dict['Outlier Names']:
		current_line.append(ev_name)
		for name in onset_dict_names[1:]:
			current_line.append(str(onset_dict[name][item_num + 1]))
		current_line.append(str(auc_dict['AUC'][item_num + 1]))
		for blank in range(14):
			current_line.append('')
		novelty_peak_onset_output.write(','.join(current_line) + '\n')
	else:
		current_line.append(ev_name)
		for name in onset_dict_names[1:]:
			current_line.append(str(onset_dict[name][item_num + 1]))
		current_line.append(str(auc_dict['AUC'][item_num + 1]))
		current_line.append(str(outlier_dict['Outlier Zscore'][outlier_index]))
		current_line.append('*')
		outlier_index += 1
		for blank in range(13):
			current_line.append('')
		novelty_peak_onset_output.write(','.join(current_line) + '\n')